package org.example.huweb.lnterceptor;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.Result.ResultUtils;
import org.example.Result.StatusCode;
import org.example.exception.BusinessException;
import org.example.utils.JwtUtils;
import org.example.utils.UserIdThreadLocalStorage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;



@Slf4j
@Component
@RequiredArgsConstructor
public class loginInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("token");
        log.info("拦截  http: {} token:{}",request.getRequestURL(), token);
        // 验证token是否为空
        if (!StringUtils.hasLength(token)) {
            throw new BusinessException(StatusCode.UNAUTHORIZED, "请登录");

        }

        try {
            // 解析token
            Claims bearer = jwtUtils.parseJWT(token.replace("Bearer ", ""));
            //bearer = Map.of("uid", login.getId(), "pwd", login.getPassword());


            String uid = bearer.get("uid").toString();


            log.info("解析token成功 用户id为{}", uid);
            UserIdThreadLocalStorage.setUserId(uid);
        } catch (Exception e) {
            log.info("解析token失败 {}", e.getMessage());
            // 如果解析失败，则返回登录页面
            throw new BusinessException(StatusCode.UNAUTHORIZED, "Token验证失败");
        }
        log.info("拦截放行 http{}",request.getRequestURL());
        return true;
    }

}
